/*
 * @Date: 2020-11-27 15:53:41
 * @LastEditors: 小枫
 * @description: description
 * @LastEditTime: 2020-11-27 20:50:25
 * @FilePath: \stu-nest\src\modules\users\users.service.ts
 */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Connection, getRepository, Repository } from 'typeorm';
import { UsersEntity } from './users.entity';

export type User = any;

@Injectable()
export class UsersService {
  private readonly users: User[];

  constructor(
    @InjectRepository(UsersEntity)
    private readonly usersRepository: Repository<UsersEntity>,
    private connection: Connection,
  ) {
    this.users = [
      {
        userId: 1,
        username: 'john',
        password: 'changeme',
      },
      {
        userId: 2,
        username: 'chris',
        password: 'secret',
      },
      {
        userId: 3,
        username: 'maria',
        password: 'guess',
      },
    ];
  }

  async findOne(username: string): Promise<User | undefined> {
    return this.users.find((user) => user.username === username);
  }

  /**
   * 查询所有用户
   */
  async findAll(): Promise<UsersEntity[]> {
    return await this.usersRepository.find();
  }

  /**
   * 创建用户
   * @param user 用户实体
   */
  async create(user): Promise<UsersEntity[]> {
    const { username } = user;
    const u = await getRepository(UsersEntity).findOne({ where: { username } });
    if (u) {
      throw new HttpException(
        {
          message: 'Input data validation faild',
          error: 'name must unique',
        },
        HttpStatus.BAD_REQUEST,
      );
    }
    return await this.usersRepository.save(user);
  }
}
